package fr.obsmip.sedoo.client.misc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import fr.obsmip.sedoo.client.ClientFactory;
import fr.obsmip.sedoo.client.event.ActionEventConstant;
import fr.obsmip.sedoo.client.habilitation.HabilitationUtil;
import fr.obsmip.sedoo.client.service.MetadataServiceAsync;
import fr.obsmip.sedoo.shared.api.IsObservatory;
import fr.obsmip.sedoo.shared.domain.ObservatorySummaryDTO;
import fr.obsmip.sedoo.shared.domain.RBVUserDTO;
import fr.obsmip.sedoo.shared.util.IsObservatoryComparator;
import fr.sedoo.commons.client.callback.OperationCallBack;
import fr.sedoo.commons.client.event.ActionStartEvent;
import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.service.DefaultAbstractCallBack;

public class ObservatoryListUtil 
{

	public static void getAvailableObservatories(ArrayList<IsObservatory> observatories, ClientFactory clientFactory, MetadataServiceAsync metadataServiceAsync, final OperationCallBack callBack) 
	{
		final List<IsObservatory> filterByUser = HabilitationUtil.filterByUser(observatories, (RBVUserDTO) clientFactory.getUserManager().getUser()); 
		if (filterByUser.isEmpty())
		{
			callBack.postExecution(true, new ArrayList<ObservatorySummaryDTO>());
		}
		else
		{
			final ActionStartEvent e = new ActionStartEvent(CommonMessages.INSTANCE.loading(), ActionEventConstant.OBSERVATORIES_LOADING_EVENT, true);
			clientFactory.getEventBus().fireEvent(e);
			final ArrayList<ObservatorySummaryDTO> aux = new ArrayList<ObservatorySummaryDTO>();
			
			metadataServiceAsync.getObservatorySummaries(clientFactory.getDisplayLanguages(), new DefaultAbstractCallBack<ArrayList<ObservatorySummaryDTO>>(e, clientFactory.getEventBus())	{
				@Override
				public void onSuccess(ArrayList<ObservatorySummaryDTO> result) {
					super.onSuccess(result);
					ListIterator<ObservatorySummaryDTO> iterator = result.listIterator();
					while (iterator.hasNext()) 
					{
						ObservatorySummaryDTO current = (ObservatorySummaryDTO) iterator.next();
						if (isInList(filterByUser, current))
						{
							aux.add(current);
						}
					}
					Collections.sort(aux, new IsObservatoryComparator());
					callBack.postExecution(true, aux);
				}
				
				private boolean isInList(List<IsObservatory> list, IsObservatory observatory)
				{
					Iterator<IsObservatory> iterator = list.iterator();
					while (iterator.hasNext()) 
					{
						IsObservatory isObservatory = iterator.next();
						if (observatory.getName().compareToIgnoreCase(isObservatory.getName())==0)
						{
							return true;
						}
					}
					return false;
				}
				
			});
		}
	}
	
}
